package com.example.leixin.helloworld.persist;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.leixin.helloworld.R;

public class SharedPreferenceActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preference);

        Button button_save_data = (Button) findViewById(R.id.button_save_data);
        button_save_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putString("name", "Tom");
                editor.putInt("age", 28);
                editor.putBoolean("married", false);
                editor.apply();
            }
        });

        Button button_restore_data = (Button) findViewById(R.id.button_restore_data);
        button_restore_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
                String name = pref.getString("name", "");
                int age = pref.getInt("age", 0);
                boolean married = pref.getBoolean("married", false);
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("name:" + name + " age:" + age + " married:" + married);
                Toast.makeText(SharedPreferenceActivity.this, stringBuilder.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
